package com.example.consumerdemo.controller;

import com.example.consumerdemo.client.UserClient;
import com.example.consumerdemo.pojo.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.cloud.client.discovery.DiscoveryClient;

import java.util.List;


@RestController
@RequestMapping("/consumer")
@Slf4j
public class ConsumerController {
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private UserClient userClient;

    @GetMapping("{id}")
    @HystrixCommand(fallbackMethod = "queryByIdFallback")
    public User queryById(@PathVariable Long id){
        //没有注册中心手动调用服务
        /*String url = "http://localhost:9091/user/" + id;
        return restTemplate.getForObject(url, User.class);*/

        //获取eureka中注册的user-service实例列表
        /*List<ServiceInstance> serviceInstanceList = discoveryClient.getInstances("user-service");
        ServiceInstance serviceInstance = serviceInstanceList.get(0);
        String url = "http://"+serviceInstance.getHost()+":"+serviceInstance.getPort()+"/user/" + id;
        return restTemplate.getForObject(url,User.class);*/

        //ribbon负载均衡
        /*String url = "http://user-service/user/" + id;
        return restTemplate.getForObject(url,User.class);*/

        //feign
        return userClient.queryById(id);
    }

    public User queryByIdFallback(Long id){
        log.error("查询用户信息失败。id：{}", id);
        return new User();
    }

}
